﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Csharp.DouyinClear.Test
{
    internal class Program
    {
        //欢迎关注的公众号net分享
        //https://www.cnblogs.com/stulzq/p/9219085.html
        //.NET Core 控制台应用程序使用异步（Async）Main方法
        private static async Task Main(string[] args)
        {
            try
            {
                var str = "3.51 LjC:/ 醒的真早呀美女  https://v.douyin.com/FYTHEm7/ 复制此链接，打开Dou音搜索，直接观看视频！";
                // 正则获取 -- https://v.douyin.com/FY95k3u/
                var videoid = "";//视频的id
                var url = Regex.Matches(str, @"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)").FirstOrDefault();
                if (url is null) Console.WriteLine("未找到视频地址");  //https://v.douyin.com/FY95k3u/ 复制此链接
                Regex reg = new Regex(@"[\u4e00-\u9fa5]");
                var targetlink = reg.Replace(url.Value, ""); //去除中文 

                // 第一步获取视频的id
                using (var center = new HttpClient())
                {
                    var message = await center.GetAsync(targetlink);
                    targetlink = message.RequestMessage.RequestUri.ToString();
                    videoid = Regex.Replace(targetlink, @"[^0-9]+", "");//视频的id
                }  
                if (string.IsNullOrEmpty(videoid))
                {
                    throw new Exception("未找到视频地址");
                }

                // 第二步 通过抖音接口获取播放地址 https://www.douyin.com/web/api/v2/aweme/iteminfo/?item_ids=
                var douyinurl = "https://www.douyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + videoid;
                var retString = "";
                using (var webClient = new System.Net.Http.HttpClient())
                {
                    retString = await webClient.GetStringAsync(douyinurl);
                }

                var jo = JObject.Parse(retString);
                var douyinvideo = jo["item_list"][0]["video"]["play_addr"]["url_list"][0].ToString();
                if (string.IsNullOrEmpty(douyinvideo))
                {
                    throw new Exception("未找到视频地址");
                }
                douyinvideo = douyinvideo.Replace("720p", "1080p"); //好像没啥作用
                                                                    // 第三步 返回视频链接
                douyinvideo = douyinvideo.Replace("aweme.snssdk.com/aweme/v1/playwm", "aweme.snssdk.com/aweme/v1/play");
                Console.WriteLine(douyinvideo);

                //抖音视频链接
                using (var center = new HttpClient())
                {
                    // 获取重定向链接（重定向之后才是视频的下载链接） 
                    center.DefaultRequestHeaders.Add("user-agent", " Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
                    var message = await center.GetAsync(douyinvideo);
                    douyinvideo = message.RequestMessage.RequestUri.ToString();
                    if (string.IsNullOrEmpty(douyinvideo))
                    {
                        throw new Exception("未找到视频地址");
                    }
                }

                //抖音视频保存
                using (var webClient = new System.Net.Http.HttpClient())
                {
                    var stream = await webClient.GetByteArrayAsync(douyinvideo);
                    var fileStream = new FileStream($"{videoid}.mp4", FileMode.Create, FileAccess.Write);
                    fileStream.Write(stream, 0, stream.Length);
                    fileStream.Dispose();

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
    }
}